package com.xiaolai.iodemo.clientcore;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;

import com.xiaolai.iodemo.graphics.MyTips;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocketConnection {
    int myport = 12346;
    InetAddress myaddress = null;
    String myalias;
    String strRec;
    BufferedReader in;
    PrintWriter out;
    Socket socket;
    Context mycontext;


    public ClientSocketConnection(Context context, String IP, int PORT, String Alias) {
        myport = PORT;
        myalias = Alias;
        mycontext = context;
    }

    public void createConn() {
        //建立套接字
        try {
            socket = new Socket(myaddress, myport);
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            Thread clientThread = new Thread();
        } catch (Exception e) {
            MyTips.showToastText(mycontext, "建立连接失败");
        }
    }

    //发送一行信息
    public void sendMsg(String Msg) {
        createConn();
        if (socket.isConnected()) out.println(Msg);
        else MyTips.showToastText(mycontext, "还没有建立连接");
    }

    //读取一行信息.
    public String recMsg() {
        try {strRec = in.readLine();
        } catch (IOException e) {
            MyTips.showToastText(mycontext, "还没有建立连接");
        }
        return strRec;
    }

    //关闭套接字连接
    public void close() {
        try {
            socket.close();
        } catch (IOException e) {
            MyTips.showToastText(mycontext, "连接已经关闭");
        }

    }


}
